/*-
 * Copyright (c) 2007-2008 SINA Corporation, All Rights Reserved.
 *  Authors:
 *      Zhu Yan <zhuyan@staff.sina.com.cn>
 *
 * Implementation
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>
#include <curl/curl.h>

#include "libprotocol.h"
#include "log.h"
#include "pic_download.h"
#include "monitor.h"

int protocol_init(char *);


static void 
pic_data_cleaner(void *data)
{
	DATA_BUFFER_NODE *dbnp;
	DATA_BUFFER_NODE *tmpdbnp;
	PIC_DATA *pdp = (PIC_DATA *)data;

	/* free the data buffer list */
	TAILQ_FOREACH_SAFE(dbnp, &(pdp->data_buffer_head),
		data_buffer_entries, tmpdbnp) {
		TAILQ_REMOVE(&(pdp->data_buffer_head), dbnp, data_buffer_entries);
		free(dbnp->data);
		free(dbnp);
		dbnp = NULL;
	}

	sfree(pdp);
}

static uint64_t downloaded = 0;

static ssize_t 
pic_data_responder(CONN_INFO *cip, void *data, int flag)
{
	PIC_DATA *pdp;
	CSF_UNUSED_ARG(cip);
	CSF_UNUSED_ARG(flag);

	pdp = (PIC_DATA *)data;
	if (pdp->ok)
		downloaded += pdp->data_len;

	return (0);
}


static void * 
pic_session_start(CONN_INFO *cip)
{
	CSF_UNUSED_ARG(cip);

	return NULL;
}

static void 
pic_session_end(CONN_INFO *cip, void *ptr)
{
	CSF_UNUSED_ARG(cip);
	CSF_UNUSED_ARG(ptr);

	return;
}

char ipstr[32];

/*
 * The data format:pic_url%space%pic_path
 */
static int 
pic_session_entry(void *rqstpp, CONN_INFO *cip, 
void *cli_info, void *data, int len)
{
	char sep = ' '; 
	char *pos = NULL;
	PIC_DATA *pdp;

	char *start = (char *)data;
	int64_t r;

	CSF_UNUSED_ARG(cli_info);
	CSF_UNUSED_ARG(len);

	if (data == NULL)
		return (-1);

	if (data == NULL)
		return (-1);
	start[len] = '\0';

	ip2str(cip, ipstr, 16);

	WLOG_DEBUG("%s in: %s", ipstr, start);

	pdp = (PIC_DATA *)smalloc(sizeof(PIC_DATA));
	
	pos = index(start, (int)sep);
	strlcpy(pdp->pic_url, start, pos - start);
	//pdp->pic_url[pos - start] = '\0';
	strlcpy(pdp->pic_path, pos + 1, len - (pos - start)- 1);
	//pdp->pic_path[len - (pos - start) - 1] = '\0';

	pdp->block_num = 0;
	pdp->data_len = 0;
	pdp->is_default = 0;
	pdp->is_deleted = 0;

	TAILQ_INIT(&pdp->data_buffer_head);
 
	r = submit_request(rqstpp, 0, pdp, 
		pic_data_cleaner, pic_data_responder, REQUEST_NONE);
	if (r < 0) {
		sfree(pdp);
	}
	return (0);
}


int 
protocol_init(char *proto_name)
{
    CSF_UNUSED_ARG(proto_name);
    set_protocol_session_start(pic_session_start);
	set_protocol_session_entry(pic_session_entry);
	set_protocol_session_end(pic_session_end);
    
//    monitor_var_register( "main", "downloaded", MNT_TYPE_UINT64, &downloaded);
	curl_global_init(CURL_GLOBAL_ALL);
	return (PROTOCOL_OK);
}


